//
//  LSCollectionViewController.m
//  LibraryStorm
//
//  Created by Enel@Lightning on 4/7/14.
//  Copyright (c) 2014 3ATeam. All rights reserved.
//

#import "LSCollectionViewController.h"
#import "LSAddCollectionViewController.h"
#import "LSMainViewController.h"

#import "LSCoreDataController.h"
#import "BookCollection.h"

#import "UIColor+HexString.h"
#import "LSCollectionCell.h"

static NSString * const CollectionCellIdentifier = @"CollectionCellId";
@interface LSCollectionViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong) NSArray *collections;
@property (nonatomic, getter = isEditingCollection) BOOL editingCollection;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) UIBarButtonItem *editButton;
@property (nonatomic, strong) UIBarButtonItem *cancelButton;
@property (nonatomic, strong) UIBarButtonItem *doneButton;
@property (nonatomic, strong) NSIndexPath *selectedIndexPath;
@end

@implementation LSCollectionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IS_DEVICE_IPAD) {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:Color_Orange_View];
        self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    // TODO: Add 3 button: done, edit, cancel on navigationBar
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 0, 40, 40);
    [doneButton setTitle:@"Done" forState:UIControlStateNormal];
    doneButton.titleLabel.font = Roboto_Regular(14);
    [doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [doneButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [doneButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
    [doneButton addTarget:self action:@selector(clickDoneButton:) forControlEvents:UIControlEventTouchUpInside];
    self.doneButton = [[UIBarButtonItem alloc] initWithCustomView:doneButton];
    self.navigationItem.leftBarButtonItem = self.doneButton;
    
    UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    editButton.frame = CGRectMake(0, 0, 40, 40);
    [editButton setTitle:@"Edit" forState:UIControlStateNormal];
    editButton.titleLabel.font = Roboto_Regular(14);
    [editButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [editButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [editButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
    [editButton addTarget:self action:@selector(clickEditButton:) forControlEvents:UIControlEventTouchUpInside];
    self.editButton = [[UIBarButtonItem alloc] initWithCustomView:editButton];
    self.navigationItem.rightBarButtonItem = self.editButton;
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(0, 0, 44, 44);
    [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = Roboto_Regular(14);
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [cancelButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];
    [cancelButton addTarget:self action:@selector(clickCancelButton:) forControlEvents:UIControlEventTouchUpInside];
    self.cancelButton = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
    
    // Do any additional setup after loading the view.
    // TODO: Custom background color
    [self.view setBackgroundColor:[UIColor colorWithHexString:Color_Orange_View]];
    [self.tableView setBackgroundColor:[UIColor whiteColor]];
    [self setTitle:NSLocalizedString(@"Collections", nil)];
    
    self.managedObjectContext = [[LSCoreDataController sharedInstance] newManagedObjectContext];
    [self loadRecordsFromCoreData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.tableView setEditing:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([[segue identifier] isEqualToString:@"addBookToCollectionId"]) {
        LSAddCollectionViewController *addViewController = [segue destinationViewController];
        if ([sender isKindOfClass:[BookCollection class]]) {
            addViewController.managedObjectId = [(BookCollection *)sender objectID];
            [addViewController setSelectBooksCompletionBlock:^{
                self.editingCollection = NO;
                [self updateButtonsToMatchTableState];
                [self loadRecordsFromCoreData];
                [self.tableView reloadData];
            }];
        }
    }
}

#pragma mark - UITableViewDataSource
/**
 * Method name: tableView:numberOfRowsInSection
 * Description: Add 1 more cell which create newCollection
 * Parameters: UITableView, Section
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.collections.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSCollectionCell *cell = [tableView dequeueReusableCellWithIdentifier:CollectionCellIdentifier forIndexPath:indexPath];
    
    if (indexPath.row == 0) {
        cell.titleLabel.text = NSLocalizedString(@"NewCollection", nil);
        cell.iconImageView.image = ICON_ADD;
    }else {
        if (indexPath.row <= self.collections.count) {
            BookCollection *collection = [self.collections objectAtIndex:indexPath.row-1];
            NSArray *books = (NSArray *)collection.bookIds;
            NSString *collectionName = collection.name;
            if (books && books.count > 0) {
                // Show collection name + number books on collection
                collectionName = [NSString stringWithFormat:@"%@ (%lu %@)", collection.name, (unsigned long)books.count, NSLocalizedString(@"BookTitle", nil)];
            }
            
            cell.titleLabel.text = collectionName;
            cell.iconImageView.image = nil;
            if (self.selectedIndexPath && self.selectedIndexPath.row == indexPath.row) {
                // Show checkMark icon when cell selected
                cell.iconImageView.image = ICON_SELECTED;
            }
        }
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        // Show alertView to user input text
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"NewCollection", nil) message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
        [alertView show];
    }else {
        // Case 1: Dismiss collectionView if not isEditingCollection
        // Case 2: If isEditingCollection that allow user edit books on collection
        if (indexPath.row <= self.collections.count) {
            BookCollection *collection = [self.collections objectAtIndex:indexPath.row-1];
            self.selectedIndexPath = indexPath;
            if (self.isEditingCollection) {
                [self setEditingCollection:NO];
                [self performSegueWithIdentifier:@"addBookToCollectionId" sender:collection];
            }else {
                [self dismissCollectionView];
            }
        }
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
/**
 * Method name: tableView:deleteCell
 * Description: Allow user delete cell if user click editButton on navigationBar.
 * Parameters: nil
 */
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isEditingCollection) {
        return UITableViewCellEditingStyleDelete;
    }
    
    return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row > 0) {
        return YES;
    }
    
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (indexPath.row <= self.collections.count) {
            BookCollection *collection = [self.collections objectAtIndex:indexPath.row-1];
            [self.managedObjectContext performBlockAndWait:^{
                [self.managedObjectContext deleteObject:collection];
                NSError *error = nil;
                BOOL saved = [self.managedObjectContext save:&error];
                if (!saved) {
                    NSLog(@"Unable to save context after deleting records for class Collection because %@", error);
                }
                [[LSCoreDataController sharedInstance] saveMasterContext];
            }];
            if (self.selectedIndexPath == indexPath) {
                self.selectedIndexPath = nil;
            }
            
            [self loadRecordsFromCoreData];
            [self.tableView reloadData];
        }
    }
}

#pragma mark - Alert view Delegate
/**
 * Method name: alertView:clickedButtonAtIndex
 * Description: Show alertView with type: textInputType. Allow user create new collection.
 * Parameters: UIAlertView, buttonIndex
 */
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != alertView.cancelButtonIndex) {
        UITextField *textField = [alertView textFieldAtIndex:0];
        if (textField && textField.text.length > 0) {
            BookCollection *collection = [NSEntityDescription insertNewObjectForEntityForName:@"BookCollection" inManagedObjectContext:self.managedObjectContext];
            NSString *collectionName = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            [collection setValue:collectionName forKey:@"name"];
            
            [self.managedObjectContext performBlockAndWait:^{
                NSError *error = nil;
                BOOL saved = [self.managedObjectContext save:&error];
                if (!saved) {
                    // do some real error handling
                    NSLog(@"Could not save Collection due to %@", error);
                }
                [[LSCoreDataController sharedInstance] saveMasterContext];
            }];
            
            [self loadRecordsFromCoreData];
            [self.tableView reloadData];
        }
    }
}

#pragma mark - Target Action
/**
 * Method name: Target Action
 * Description: Change position, value of barButtonItem.
 * Parameters: UIButton
 */
- (void)clickDoneButton:(id)sender
{
    if (!self.isEditingCollection) {
        [self dismissCollectionView];
    }else {
        self.editingCollection = NO;
        [self updateButtonsToMatchTableState];
    }
}

- (void)clickEditButton:(id)sender
{
    self.editingCollection = YES;
    [self updateButtonsToMatchTableState];
}

- (void)clickCancelButton:(id)sender
{
    self.editingCollection = NO;
    [self updateButtonsToMatchTableState];
}

#pragma mark - Load Records
/**
 * Method name: loadRecordsFromCoreData
 * Description: Load all collection which saved on core data. Using when user create or delete collection.
 * Parameters: nil
 */
- (void)loadRecordsFromCoreData
{
    self.collections = [BookCollection getAllObjectsInContext:self.managedObjectContext withSortDescriptor:nil resetContext:YES fetchLimit:0];
}

#pragma mark - Dismiss Collection View
/**
 * Method name: dismissCollectionView
 * Description: Handle when user click done button or select collection. Pass collectionManagedObjectId to mainViewController to filter book.
 * Parameters: nil
 */
- (void)dismissCollectionView
{
    if ([self.presentingViewController isKindOfClass:[MMDrawerController class]]) {
        MMDrawerController *mm_drawerController = (MMDrawerController *)self.presentingViewController;
        LSMainViewController *mainViewController = nil;
        if ([mm_drawerController.centerViewController isKindOfClass:[UINavigationController class]]) {
            if ([[(UINavigationController *)mm_drawerController.centerViewController topViewController] isKindOfClass:[LSMainViewController class]]) {
                mainViewController = (LSMainViewController *)[(UINavigationController *)mm_drawerController.centerViewController topViewController];
            }
            
            if ([(UINavigationController *)mm_drawerController.centerViewController viewControllers].count > 1) {
                [(UINavigationController *)mm_drawerController.centerViewController popToRootViewControllerAnimated:YES];
                if ([[(UINavigationController *)mm_drawerController.centerViewController viewControllers][0] isKindOfClass:[LSMainViewController class]]) {
                    mainViewController = (LSMainViewController *)[(UINavigationController *)mm_drawerController.centerViewController viewControllers][0];
                }
            }
        }
        
        if (self.collections.count > 0) {
            if (self.selectedIndexPath && self.selectedIndexPath.row <= self.collections.count) {
                // Pass managedObjectID of collection to mainViewController
                BookCollection *collection = [self.collections objectAtIndex:self.selectedIndexPath.row - 1];
                mainViewController.collectionManagedObjectID = [collection objectID];
            }else {
                mainViewController.collectionManagedObjectID = nil;
            }
        }else {
            mainViewController.collectionManagedObjectID = nil;
        }
        
        [mainViewController showListBook:LSMenuLeftCollections withCategoryType:-1];
        [self dismissViewControllerAnimated:YES completion:^{
            [mm_drawerController closeDrawerAnimated:YES completion:NULL];
        }];
    }else if (IS_DEVICE_IPAD && self.mm_drawerController && self.popOverController) {
        LSMainViewController *mainViewController = nil;
        if ([self.mm_drawerController.centerViewController isKindOfClass:[UINavigationController class]]) {
            if ([[(UINavigationController *)self.mm_drawerController.centerViewController topViewController] isKindOfClass:[LSMainViewController class]]) {
                mainViewController = (LSMainViewController *)[(UINavigationController *)self.mm_drawerController.centerViewController topViewController];
            }
            
            if ([(UINavigationController *)self.mm_drawerController.centerViewController viewControllers].count > 1) {
                [(UINavigationController *)self.mm_drawerController.centerViewController popToRootViewControllerAnimated:YES];
                if ([[(UINavigationController *)self.mm_drawerController.centerViewController viewControllers][0] isKindOfClass:[LSMainViewController class]]) {
                    mainViewController = (LSMainViewController *)[(UINavigationController *)self.mm_drawerController.centerViewController viewControllers][0];
                }
            }
        }
        if (self.collections.count > 0) {
            if (self.selectedIndexPath && self.selectedIndexPath.row <= self.collections.count) {
                // Pass managedObjectID of collection to mainViewController
                BookCollection *collection = [self.collections objectAtIndex:self.selectedIndexPath.row - 1];
                mainViewController.collectionManagedObjectID = [collection objectID];
            }else {
                mainViewController.collectionManagedObjectID = nil;
            }
        }else {
            mainViewController.collectionManagedObjectID = nil;
        }
        
        [mainViewController showListBook:LSMenuLeftCollections withCategoryType:-1];
        [self.mm_drawerController closeDrawerAnimated:YES completion:NULL];
        [self.popOverController dismissPopoverAnimated:YES];
    }
}

#pragma mark - Updating button state
/**
 * Method name: updateButtonsToMatchTableState
 * Description: Update buttons on navigation bar
 * Parameters: nil
 */
- (void)updateButtonsToMatchTableState
{
    if (self.isEditingCollection) {
        // Show the option to cancel the done.
        self.navigationItem.leftBarButtonItem = self.cancelButton;
        // Show the done button.
        self.navigationItem.rightBarButtonItem = self.doneButton;
    }else {
        // Not in editing mode.
        self.navigationItem.leftBarButtonItem = self.doneButton;
        self.navigationItem.rightBarButtonItem = self.editButton;
    }
}
@end
